Thumb

JavaScript Object Accessors

1/22/2020 4:31:35 AM

The JavaScript accessors introduce in the ECMAScript 5 in 2009. In the JavaScript have two accessors like get and set accessor. This accessor is allowed to get the value out of the object scope and set accessors   allow to the set value into object variables or property. Some other programming like C# or java have this accessor. This getting and setting accessors are very important also JavaScript. We use this accessor into the JavaScript object. Now given bellow the JavaScript accessor example code and explain the code:

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<script type="text/javascript">
    //object Accessors 
var mYobj = {
  id     : 1,
  Name: "Farhan Sakib",
 //set Accessors
 set lang(id) {
    return this.id=id;
  },

  //get Accessors
 get lang() {
    return this.Name +" - "+this.id;
  },
};
//assgin the value by set Accessors
mYobj.id=102;
// Show data from the object using get Accessors
 console.log(mYobj.lang);
</script>
</body>
</html>

In this JavaScript code we show the how to work get and set Accessors. First, we create an object this object contains the two property or variables. This property holds the default value then we use the set   Accessors to assign the new value by overloading the default value. Now we use the get Accessors for get the values and show the update value using “console.log” from out of the object.